﻿using System.IO;
using System;
using System.Collections.Generic;
using System.Text;

namespace xReplace
{
    class OutputObject
    {
        public OutputObject(Project p, string overrideDestinationPath, string overrideDestinationSingleFile)
        {
            this.path = p.GetKey("output", "path");
            if (overrideDestinationPath != "") this.path = overrideDestinationPath;
            if (!this.path.EndsWith("\\")) this.path += "\\";
            this.clean = p.GetKeyAsBoolean("output", "clean");
            this.flatten = p.GetKeyAsBoolean("output", "flatten");
            this.renameRules = p.GetKey("output", "renameRules");
            this.singleFile = p.GetKey("output", "singleFile");
            if (overrideDestinationSingleFile != "") this.singleFile = overrideDestinationSingleFile;
        }

        public string path;
        public bool clean;
        public bool flatten;
        public string renameRules;
        public string singleFile;

        public void WriteContent(string outputFilename, string content)
        {
            if (this.singleFile == "")
            {
                if (!Directory.Exists(Path.GetDirectoryName(outputFilename))) Directory.CreateDirectory(Path.GetDirectoryName(outputFilename));
                File.WriteAllText(outputFilename, content);
            }
            else
            {
                File.AppendAllText(outputFilename, content);
            }
        }

        public string GetOutputFilename(InputObject i, string fileName)
        {
            string outputFilename = fileName.Replace(i.path, this.path);
            if (this.singleFile == "")
            {
                if (this.flatten == true)
                {
                    string tmpPath = outputFilename.Replace(this.path, "");
                    string flatPath = tmpPath.Replace("\\", "_");
                    outputFilename = Path.Combine(this.path, flatPath);
                }

                if (this.renameRules != "") outputFilename = RenameHelper.PerformRename(outputFilename, this.renameRules);
            }
            else
            {
                outputFilename = this.singleFile;
            }
            return outputFilename;
        }
    }
}
